package com.scrum.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import javax.websocket.Session;

import com.scrum.Object.Catalog;
import com.scrum.Object.File_Process;
import com.scrum.Object.Post;
import com.scrum.Object.User;

/**
 * Servlet implementation class Update_User
 */
@WebServlet("/user/update_user")
@MultipartConfig
public class Update_User extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Update_User() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	String filePath = getServletContext().getInitParameter("user_file_upload"); 
    Part filePart = request.getPart("browse_user"); // Retrieves <input type="file" name="file">
    HttpSession session = (HttpSession) request.getSession();
    User user = ((User)session.getAttribute("currentuser"));
    String filename;
    try{
    filename = File_Process.getFilename(filePart);
    InputStream filecontent = filePart.getInputStream();
    OutputStream  outputStream = new FileOutputStream(new File(filePath+ File.separator + filename));
    int read = 0;
    byte[] bytes = new byte[1024];

	while ((read = filecontent.read(bytes)) != -1) {
		outputStream.write(bytes, 0, read);
	}
	
    }catch(Exception ex){
    	filename = user.getImage();
    }
	String username = request.getParameter("username");
	String fullname = request.getParameter("fullname");
	String gender = request.getParameter("gender");
	String password = request.getParameter("password");
	String address = request.getParameter("address");
	String email = request.getParameter("email");
	try {
			
			User userupdate = user.update(username, password, filename, fullname, gender, address, email);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}

}
